/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.organization;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.District;
import com.qinyeit.serviceapp.entity.Employee;
import com.qinyeit.serviceapp.entity.enums.Gender;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.entity.system.ManagementAccount;
import com.qinyeit.serviceapp.entity.system.ManagementRole;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.organization.EmployeeService;
import com.qinyeit.serviceapp.service.system.ManagementAccountService;
import com.qinyeit.serviceapp.service.system.ManagementRoleService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.EnumMap;
import java.util.List;

/**
 * ClassName: EmployeesController <br/>
 * Function: employee [员工] <br/>
 * date: 2018-11-20 13:17:56 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/organization/employees")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_employee:read",name ="员工",deleteAble = false)
public class EmployeesController extends BaseManagementController{

	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private DistrictService districtService;
	@Autowired
    private ManagementAccountService managementAccountService;
	@Autowired
    private ManagementRoleService managementRoleService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","name","phone","birthday","gender","avatar","address","accountId","districtId","departmentId","state",
	"account.id","account.locked","account.name","districtName","attachDataPermission"};

    @RequiresPermissions("management_employee:show")
    @PermissionInfo(code = "management_employee:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
//        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
////        searchable.addSearchParam("account.admin_eq",false);
//        searchable.addSearchFilter(SearchFilterHelper.or(
//                SearchFilterHelper.newCondition("account", SearchOperator.isNull,null)
////                SearchFilterHelper.newCondition("account.admin",SearchOperator.eq,false)
//        ));

//        Page<Employee> employeePage = employeeService.findAll(searchable);

        QyMap map = QyMap.NEW();
        map.setv("employeePage",employeeService.findallPage(searchable,CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
        initFormDate(map);
        return ok("查询成功", map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("employee",JSONUtils.include(new Employee(), keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_employee:create")
    @PermissionInfo(code = "management_employee:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid Employee employee, BindingResult bindingResult){
//        if(employeeService.exists(buildExists(null, "no", employee.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        if(StringUtils.isBlank(employee.getName())){
            throw new BusinessRunTimeException("请填写名称",10001);
        }
        if (StringUtils.isBlank(employee.getPhone())) {
            throw new BusinessRunTimeException("请填写手机号码",10001);
        }
        if(employee.getDistrictId()==null){
            throw new BusinessRunTimeException("请选择区域",10002);
        }
        employee.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        employee.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        employeeService.save(employee);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute Employee employee){
        return ok("查询成功", JSONUtils.include(employee, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute Employee employee){
        QyMap map=QyMap.NEW();
        employee.setDistrictName(districtService.findById(employee.getDistrictId()).getParentId().toString());
        map.setv("employee",JSONUtils.include(employee, keys));
        initFormDate(map);

        //
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_employee:update")
    @PermissionInfo(code = "management_employee:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid Employee employee,BindingResult bindingResult){
//        if(employeeService.exists(buildExists(null, "no", employee.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        if(StringUtils.isBlank(employee.getName())){
            throw new BusinessRunTimeException("请填写名称",10001);
        }
        if (StringUtils.isBlank(employee.getPhone())) {
            throw new BusinessRunTimeException("请填写手机号码",10001);
        }
        if(employee.getDistrictId()==null){
            throw new BusinessRunTimeException("请选择区域",10002);
        }
        employee.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        employee.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        employeeService.update(employee);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_employee:destory")
    @PermissionInfo(code = "management_employee:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){

        //id
        Employee employee = employeeService.findById(id);
        ManagementAccount account = employee.getAccount();
//        if(account!=null){
//            throw new BusinessRunTimeException("该员工已绑定账号，不能删除",10001);
//        }
        //删除员工 将账号删除
        managementAccountService.logicDelete(account.getId());
        employeeService.logicDelete(id);

        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            Employee employee = employeeService.findById(Long.valueOf(id));
            model.addAttribute(employee);
        }
    }

    /**
     * 分配账号初始化
     * @param employeeId
     * @return
     */
    @GetMapping("/allocationAccount")
    public Object allocationAccount(Long employeeId){
        QyMap map=QyMap.NEW();
        Employee employee = employeeService.findById(employeeId);
        //获取角色
        map.setv("positions",JSONUtils.include(managementRoleService.getPositions(CurrentAccountUtils.getAuthenticatedMerchantGroupID()),"id","code","name","type","description"));
        if(employee.getAccount()!=null){
            map.setv("account",JSONUtils.include(employee.getAccount(),"id","account"));
            //部门id
           QyMap qyMap = employeeService.getRoles(employee.getAccount().getId());
           map.setv("roles",qyMap.get("ids"));
        }
        return ok("查询成功",map);
    }

    /**
     * 分配账号初始化
     * @param data
     * @return
     */
    @RequiresPermissions("management_employee:allocationAccount")
    @PermissionInfo(code = "management_employee:allocationAccount",name ="分配账号",deleteAble = false)
    @PostMapping("/allocationAccount")
    public Object allocationAccountsave(@RequestBody JSONObject data){
        QyMap map=QyMap.NEW();
        managementAccountService.saveAccount(data, CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("操作成功",map);
    }

    /**
     * 修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_employee:updateState")
    @PermissionInfo(code = "management_employee:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        //停用
        Employee employee = employeeService.findById(id);
        ManagementAccount account=null;
        if(employee.getState()==State.NORMAL){
            employee.setState(State.DISABLED);
            account = employee.getAccount();
            if(account!=null){
                account.setLocked(true);
                managementAccountService.update(account);
            }
//            = managementAccountService.findById(employee.getAccount().getId());
            if(account!=null){

            }
        }else {
            employee.setState(State.NORMAL);
            account = employee.getAccount();
//            account = managementAccountService.findById(employee.getAccount().getId());
            if(account!=null){
                account.setLocked(false);
                managementAccountService.update(account);
            }
        }
        employeeService.update(employee);
        return ok("操作成功", null);
    }



    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        qyMap.setv("genders", Gender.values());
        //区域
        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        qyMap.setv("districts",list);
        qyMap.setv("states",State.values());

    }

}